/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.customize.enums.CommonDictEnum;
import com.pig4cloud.pigx.common.customize.exception.DuckweedException;
import com.pig4cloud.pigx.common.customize.mysql.utils.MysqlUtil;
import com.pig4cloud.pigx.common.customize.redis.constants.CommonRedisConstants;
import com.pig4cloud.pigx.common.customize.redis.constants.RedisKeyEnum;
import com.pig4cloud.pigx.common.customize.redis.utils.RedisUtils;
import com.pig4cloud.pigx.common.customize.security.utils.SecurityUtil;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.system.constant.RedisHashKeyConstant;
import com.pig4cloud.pigx.system.constant.SystemPlatformConstant;
import com.pig4cloud.pigx.system.dto.SystemSymbolAddDTO;
import com.pig4cloud.pigx.system.dto.SystemSymbolEditDTO;
import com.pig4cloud.pigx.system.entity.SystemProduct;
import com.pig4cloud.pigx.system.entity.SystemSymbol;
import com.pig4cloud.pigx.system.mapper.SystemProductMapper;
import com.pig4cloud.pigx.system.mapper.SystemSymbolMapper;
import com.pig4cloud.pigx.system.mapstruct.SystemSymbolStruct;
import com.pig4cloud.pigx.system.service.SystemSymbolService;
import com.pig4cloud.pigx.system.vo.SystemSymbolOptionVO;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 币对
 *
 * @since 2022-11-23 15:15:20
 */
@Service
@RequiredArgsConstructor
public class SystemSymbolServiceImpl extends ServiceImpl<SystemSymbolMapper, SystemSymbol> implements SystemSymbolService {

    private final SystemProductMapper systemProductMapper;

    private final SecurityUtil securityUtil;
    private final RedisUtils redisUtils;

    private final RedisTemplate redis;

    private final MysqlUtil mysqlUtil;

    /**
     * 分页查询
     *
     * @param page      分页条件
     * @param condition 查询条件
     * @return {@link Page <  SystemSymbol >}
     * @since 2022/11/24 10:48
     */
    @Override
    public Page<SystemSymbol> page(Page<SystemSymbol> page, SystemSymbol condition) {

        QueryWrapper<SystemSymbol> query = new QueryWrapper<>();
        query.lambda()
                .like(Strings.isNotBlank(condition.getName()), SystemSymbol::getName, condition.getName())
                .orderByDesc(SystemSymbol::getCreateTime);

        return baseMapper.selectPage(page, query);

    }

    /**
     * 新增
     *
     * @param dto 数据
     * @since 2022/11/24 11:31
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void add(SystemSymbolAddDTO dto) {

        SystemSymbol entity = SystemSymbolStruct.INSTANCE.addDTO2entity(dto);
        PigxUser user = SecurityUtil.getLoginUserNotNull();
        LocalDateTime now = LocalDateTime.now();

        entity.setCreateName(user.getName());
        entity.setUpdateName(user.getName());
        securityUtil.initCreateAbout(entity, user, now);

        if (baseMapper.add(entity) != 1) {
            String errorMsg = String.format("名称为{%s}的数据已存在", dto.getName());
            throw new DuckweedException(errorMsg);
        }

        // 刷新缓存
        redisUtils.flushPersistentCache(RedisKeyEnum.SYMBOL, entity.getName(), entity);
        updateRedis();
    }

    /**
     * 修改
     *
     * @param dto 数据
     * @since 2022/11/24 11:31
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void edit(SystemSymbolEditDTO dto) {

        SystemSymbol entity = baseMapper.selectById(dto.getId());
        if (Objects.isNull(entity)) {
            throw new DuckweedException("数据状态已变化");
        }

        if (!Objects.equals(entity.getName(), dto.getName())) {
            // 检查引用
            checkReferences(entity.getName());
        }

        entity = SystemSymbolStruct.INSTANCE.editDTO2entity(dto);
        PigxUser user = SecurityUtil.getLoginUserNotNull();
        LocalDateTime now = LocalDateTime.now();

        entity.setUpdateName(user.getName());
        securityUtil.initUpdateAbout(entity, user, now);

        if (baseMapper.edit(entity) != 1) {
            String errorMsg = String.format("名称为{%s}的数据已存在", dto.getName());
            throw new DuckweedException(errorMsg);
        }

        // 刷新缓存
        entity = baseMapper.selectById(entity.getId());
        redisUtils.flushPersistentCache(RedisKeyEnum.SYMBOL, entity.getName(), entity);
        updateRedis();
    }

    /**
     * 根据id逻辑删除
     *
     * @param id id
     * @since 2022/11/24 11:31
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void del(Long id) {

        SystemSymbol entity = baseMapper.selectById(id);
        if (Objects.isNull(entity)) {
            throw new DuckweedException("数据状态已变化");
        }

        // 检查引用
        checkReferences(entity.getName());

        PigxUser user = SecurityUtil.getLoginUserNotNull();
        LocalDateTime now = LocalDateTime.now();

        UpdateWrapper<SystemSymbol> update = new UpdateWrapper<>();
        update.lambda()
                .set(SystemSymbol::getUpdateBy, user.getId())
                .set(SystemSymbol::getUpdateName, user.getName())
                .set(SystemSymbol::getUpdateTime, now)
                .set(SystemSymbol::getIsDeleted, null)
                .eq(SystemSymbol::getId, id);
        if (baseMapper.update(null, update) != 1) {
            throw new DuckweedException("操作失败");
        }

        // 刷新缓存
        redisUtils.delPersistentCache(RedisKeyEnum.SYMBOL, entity.getName());

    }

    /**
     * 检查引用
     *
     * @param symbolName 币对名称
     * @since 2022/11/24 16:04
     */
    private void checkReferences(String symbolName) {

        // 检查在产品表system_product中的引用
        QueryWrapper<SystemProduct> queryProduct = new QueryWrapper<>();
        queryProduct.lambda()
                .eq(SystemProduct::getName, symbolName);
        Long productCount = systemProductMapper.selectCount(queryProduct);
        if (productCount > 0) {
            throw new DuckweedException("该币对数据正在被某个产品使用");
        }

    }

    /**
     * 查询选项数据
     *
     * @return {@link List< SystemSymbolOptionVO>}
     * @since 2022/11/24 14:26
     */
    @Override
    public List<SystemSymbolOptionVO> option() {

        QueryWrapper<SystemSymbol> query = new QueryWrapper<>();
        query.lambda()
                .select(SystemSymbol::getId,
                        SystemSymbol::getName)
                .orderByAsc(SystemSymbol::getName);
        List<SystemSymbol> list = baseMapper.selectList(query);

        return SystemSymbolStruct.INSTANCE.list2OptionVOList(list);

    }

    @Override
    public void updateRedis() {
        try {
            mysqlUtil.startLocalTx();
            // 所有启用的币对
            List<SystemSymbol> list = baseMapper.selectList(new QueryWrapper<SystemSymbol>() {{
                eq("status", CommonDictEnum.Status.NORMAL.getValue());
                orderByAsc("create_time");
            }});

            redis.delete(RedisHashKeyConstant.SYMBOL_LIST);
            for (SystemSymbol symbol : list) {
                redis.opsForHash().put(RedisHashKeyConstant.SYMBOL_LIST, symbol.getName(), symbol);
                redisUtils.flushPersistentCache(RedisKeyEnum.SYMBOL, symbol.getName(), symbol);
            }
            mysqlUtil.commitLocalTx();
        } catch (Exception e) {
            mysqlUtil.rollbackLocalTx();
        }
    }

    /**
     * 获取币对价格
     *
     * @param name 币对名称
     * @return {@link BigDecimal}
     * @since 2022/12/10 15:02
     */
    @Override
    public BigDecimal getPrice(String name, Long platformId) {
        BigDecimal price = null;
        if (platformId.equals(SystemPlatformConstant.OKX)) {
            price = redisUtils.getSymbolPrice(name, CommonRedisConstants.OKX + CommonRedisConstants.LAST_PRICE);
        }
        return price;
    }
}
